#define _CRT_SECURE_NO_WARNINGS   1

#include<iostream>
using namespace std;
int main()
{
	long long int q, a, b, p;
	cin >> q;
	while (q--)
	{
		cin >> a >> b >> p;
		long long int index = b, base = 1;
		while (index)
		{
			if (index % 2 != 0)
				base = base * a;
			base = base % p;
			a = a * a;
			a = a % p;
			index /= 2;
		}
		cout << base << endl;
	}
}
